package com.czk.api.deleteTable;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;

import java.io.IOException;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/6/2 15:33
 */
public class DeleteTable {
    private static Connection connection = null;
    private static Admin admin = null;

    static {
        // 静态代码块初始化
        // 创建配置类
        Configuration configuration = HBaseConfiguration.create();
        // zookeeper连接
        configuration.set("hbase.zookeeper.quorum", "192.168.25.133");
        // 端口
        configuration.set("hbase.zookeeper.property.clientPort", "2181");
        //
        try {
            connection = ConnectionFactory.createConnection(configuration);
            admin = connection.getAdmin();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        deleteTable("stu5");
    }

    /**
     * 删除表
     *
     * @param tableName
     * @throws IOException
     */
    public static void deleteTable(String tableName) throws IOException {
        // 表是否存在
        if (!isExists(tableName)) {
            return;
        }
        // 存在
        System.out.println(tableName + "表存在");
        // 使表下线
        admin.disableTable(TableName.valueOf(tableName));
        // 删除表
        admin.deleteTable(TableName.valueOf(tableName));
        if (!isExists(tableName)){
            System.out.println("删除成功");
        }
    }

    private static boolean isExists(String tableName) throws IOException {
        return admin.tableExists(TableName.valueOf(tableName));
    }
}
